/***** Preference Dialog Functions *****/

const pBranch = Components.interfaces.nsIPrefBranch;
var gPref = Components.classes["@mozilla.org/preferences-service;1"].getService(pBranch);
var nsIPrefServiceObj = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
var winMediator= Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
var prevWindow = winMediator.getMostRecentWindow('navigator:browser');

var gPrefs;
var radiogroups;

// load all preferences into the dialog
function TM_EMinit()
{
  gPrefs =  document.getElementsByAttribute("prefstring", "*");
  radiogroups = document.getElementsByTagName("radiogroup");

  getTab();

  // show groupbox if incompatible extensions exist in this profile
  if (prevWindow.getExtensions().length == 0)
    document.getElementById("incompatible").collapsed = true;

  if ("mTabDropIndicatorBar" in prevWindow.gBrowser)
    document.getElementById("addTabDrag").hidden= true;
  else
    document.getElementById("dropIndicator").hidden= true;

  // add EventListener when we start
  window.addEventListener("command", TM_enableApply, false);
  window.addEventListener("input", TM_enableApply, false);

  // prevent non intiger key in int text box  
  window.addEventListener("keypress", keyPressInText, false);

  // create saved Session popup menu
  var popup = document.getElementById("onStart.popup");
    SessionManager.createMenuForDialog(popup);

  // update tabclicking items that aren't change by tabmix
  TM_Options.setItem("snapBack", "hidden", !(prevWindow.SessionSaver && prevWindow.SessionSaver.snapBackTab));
  var isIE = (prevWindow.IeView && prevWindow.IeView.ieViewLaunch) ||
             (prevWindow.gIeTab && prevWindow.gIeTab.switchTabEngine) ||
             (prevWindow.ieview && prevWindow.ieview.launch);
  TM_Options.setItem("ieView", "hidden", !isIE);

  // check if bookmark item in tab context menu
  TM_Options.setItem("bmMenu", "hidden", !(prevWindow.document.getElementById("tm-bookmarkAllTabs")));
  // check if book "Browser:BookmarkAllTabs" command exist
  TM_Options.setItem("bmTabsCommand", "hidden", !(prevWindow.document.getElementById("Browser:BookmarkAllTabs")));

  // update pref for 'places'
  if (prevWindow.gIsPlaces) {
    document.getElementById("openBookmarks").setAttribute("label", document.getElementById("selectTabBH").getAttribute("label"));
    document.getElementById("openHistory").hidden = true;
  }

  if (!prevWindow.gIsFirefox2) {
    var item = document.getElementById("focusOpenerTab");
    item.parentNode.removeChild(item);
    document.getElementById("focusRightTab").setAttribute("value", "2");
    document.getElementById("hideAllTabsButton").hidden = true;
    document.getElementById("sessionstore_box").hidden = true;
    document.getElementById("session_deck").selectedIndex = 1;
  }

  // Init tabclicking options
  var menuPopup = document.getElementById("tabclicking").firstChild;
  document.getElementById("ClickTab").appendChild(menuPopup.cloneNode(true));
  document.getElementById("ClickTabbar").appendChild(menuPopup.cloneNode(true));

  TM_setElements(false, true);
  // check if apply is on
  // apply changes if we set single window mode statuse
  TM_EMsave();

  setVisibility(document.getElementById("tabclicking_tabbox").selectedIndex);

  window.setTimeout( function () { window.focus();}, 0 );
}

// save all preferences entered into the dialog
function TM_EMsave(onApply)
{
  // we only need to save if apply is enabled
  if (!onApply && document.documentElement.getButton("extra1").disabled)
    return true;

  // set flag to prevent TMupdateSettings from run for each change
  gPref.setBoolPref("extensions.tabmix.setDefault", true);

  TM_Options.singleWindow( document.getElementById("singleWindow").checked );
  TM_Options.setTabXUI();
  TM_verifyWidth();
  TM_Options.verify_PostDataBytes();

  document.documentElement.getButton('accept').focus()
  document.documentElement.getButton("extra1").disabled = true;

  if (!("undefined" in applyData)) {
    for (var _pref in applyData)
      setPrefByType(_pref, applyData[_pref]);
  }
  else {
    // this part is only if the applayData fail for some unknown reason
    // we don't supposed to get here
    for (var i = 0; i < gPrefs.length; ++i )
      setPrefByType(gPrefs[i].getAttribute("prefstring"), getValue(gPrefs[i]));
  }

  // set saved sessionpath if loadsession >=0
  var val = gPref.getIntPref("extensions.tabmix.sessions.onStart.loadsession");
  var popup = document.getElementById("onStart.popup");
  var pref = "extensions.tabmix.sessions.onStart.sessionpath";
  gPref.setCharPref(pref, popup.getElementsByAttribute("value", val)[0].getAttribute("session"));

  applyData = [];
  gPref.clearUserPref("extensions.tabmix.setDefault"); // this trigger TMupdateSettings

  callUpdateSettings();

  nsIPrefServiceObj.savePrefFile(null); // store the pref immediately
  return true;
}

function callUpdateSettings() {
  var pref = "extensions.tabmix.PrefObserver.error";
  if (gPref.prefHasUserValue(pref) && gPref.getBoolPref(pref)) {
    var wnd, enumerator = winMediator.getEnumerator("navigator:browser");
    while (enumerator.hasMoreElements()) {
      wnd = enumerator.getNext();
      wnd.TMupdateSettings();
    }
  }
}

function TM_verifyWidth() {
   var minWidth = document.getElementById("minWidth");
   var maxWidth = document.getElementById("maxWidth");

   var minValue = minWidth.value;
   var maxValue = maxWidth.value;

   if (maxValue - minValue < 0) {
      minWidth.value = maxValue;
      maxWidth.value = minValue;
   }

   if (minWidth.value < 22)
     minWidth.value = 22;

   if (minValue != minWidth.value)
      updateApplyData(minWidth);

   if (maxValue != maxWidth.value)
      updateApplyData(maxWidth);

}

var TM_Options = {
   checkDependant: function(start) {

      this.singleWindow( document.getElementById("singleWindow").checked );

      var broadcasters = document.getElementById("disabled:Broadcaster");
      for (var i = 0; i < broadcasters.childNodes.length; ++i ) {
         var _id = broadcasters.childNodes[i].id.replace("obs_", "");
         this.disabled(_id, start);
      }

      this.setTabXUI();
      this.addTabXUI();
      this.selectTab();
      this.tabScroll();
      this.speLink();
      this.setAppearanceButton();
      this.newTabUrl(false);
      if (prevWindow.gIsFirefox2)
         this.setSessionsOptions(document.getElementById("sessionstore"));
      this.setDisabled("obs_ss_postdata", document.getElementById("ss_postdata").value == 2);

   },

   disabled: function(itemOrId, start) {
      var item = typeof(itemOrId) == "string" ? document.getElementById(itemOrId) : itemOrId;
      var val = item.getAttribute("inverseDependency") ? item.checked : !item.checked;
      if (start && !val)
         return;
      this.setDisabled("obs_" + item.id, val);
   },

   setDisabled: function(id, val) {
      if (val == true)
         this.setItem(id, "disabled" , val);
      else {
         // remove disabled from all observers,
         // we can't edit textbox-input with disabled=null or disabled=false
         // textbox-input inherits the dislabled attribute from the textbox

         // all broadcaster has no disabled attribute at startup
         var aBroadcaster = document.getElementById(id);
         if (aBroadcaster.hasAttribute("disabled")) {
            aBroadcaster.removeAttribute("disabled");
         }
      }
   },

   newTabUrl: function(setFocus) {
      var showTabUrlBox = document.getElementById("loadOnNewTab").selectedItem.value == 4;
      this.setDisabled("newTabUrlLabel", !showTabUrlBox);
      this.setDisabled("newTabUrl", !showTabUrlBox);
      if (setFocus && showTabUrlBox)
         document.getElementById("newTabUrl").focus();
   },

   addTabXUI: function() {
      var tabXValue = document.getElementById("addTabXUI").selectedItem.value;
      this.setItem("tabXdelaycheck", "hidden", tabXValue != 2 && tabXValue != 4);
      this.setItem("tabXwidthBox", "hidden", tabXValue != 5);
   },

   setTabXUI: function(flexTabs) {
      if (document.getElementById("flexTabs").checked) {
         var tabXUI = document.getElementById("addTabXUI");
         if ( tabXUI.selectedItem.value == 5) {
            tabXUI.value = 1;
            updateApplyData(tabXUI);
            this.addTabXUI();
         }
      }
   },

   selectTab: function() {
      var focusType = document.getElementById("selectTab").checked ? "bg":"fg";
      var val = document.getElementById("showInverseLink").getAttribute(focusType+"label");
      this.setItem("showInverseLink", "label", val);
   },

   tabScroll: function() {
      var selectedValue = document.getElementById("tabScroll").value;
      var vis = selectedValue == 2 ? "visibility: visible" : "visibility: hidden";
      this.setItem("maxbar", "style", vis);
   },

   speLink: function() {
      var spelink = document.getElementById("speLink").selectedItem.value;
      document.getElementById("inverselinks").disabled =  spelink != 2 && document.getElementById("midcurrent").checked;
   },

   setAppearanceButton: function() {
      document.getElementById("advancedAppearance").disabled = 
                              !document.getElementById("unreadTab").checked &&
                              !document.getElementById("currentTab").checked && 
                              !document.getElementById("progressMeter").checked;
   },

   singleWindow: function(enableSingleWindow) {
      if ( enableSingleWindow ) {
         function updateStatus(itemId, testVal, test, newVal) {
            var item = document.getElementById(itemId);
            test = test ? item.value == testVal : item.value != testVal
            if ( test ) {
               item.value = newVal;
               updateApplyData(item);
            }
         }

         updateStatus("externalLinkTarget", 2, true, 3);
         updateStatus("divertedWindowOpen", 0, false, 0);
         updateStatus("generalWindowOpen", 2, true, 3);
      }
   },

   verify_PostDataBytes: function() {
      var ss_postdatabytes = document.getElementById("ss_postdatabytes");
      var val = ss_postdatabytes.value;
      if (val == "-" || val == "") {
         ss_postdatabytes.value = val == "" ? "0" : "-1";
         updateApplyData(ss_postdatabytes);
      }
   },

   setSessionsOptions: function (item) {
      if (!prevWindow.gIsFirefox2)
         return;

      var useSessionManager = !item.checked;
      document.getElementById("session_deck").selectedIndex = useSessionManager ? 1 : 0;
      
      if (!useSessionManager) {
         var sessionManager = document.getElementById("sessionManager");
         sessionManager.checked = useSessionManager;
         updateApplyData(sessionManager);

         var sessionCrashRecovery = document.getElementById("sessionCrashRecovery");
         sessionCrashRecovery.checked = useSessionManager;
         updateApplyData(sessionCrashRecovery);
      }
   },

   setUndoCloseCache: function (item) {
      document.getElementById('undoCloseCache').value = item.checked ? 5 : 0;
   },

   // Set given attribute of specified item.  If the
   // value is null, then it removes the attribute (which works
   // nicely for the disabled attribute).
   setItem: function (id, attrib, val) {
      var item = document.getElementById(id);
      if (val == null)
         item.removeAttribute(attrib);
      else if (!item.hasAttribute(attrib) || item.getAttribute(attrib) != val);
         item.setAttribute(attrib, val);
   }

}

// other settings not in the main option dialog
var otherPref = ["sessions.onStart.sessionpath",
                  "filetype","boldUnread","italicUnread","underlineUnread",
                  "boldCurrent","italicCurrent","underlineCurrent","unreadColorCode",
                  "currentColorCode","progressColorCode","useCurrentColor",
                  "useUnreadColor","noprogress","useProgressColor","sessions.menu.showext",
                  "disableIncompatible","hideIcons","disableF9Key"];

function TM_defaultSetting () {
  // set flag to prevent TMupdateSettings from run for each change
  gPref.setBoolPref("extensions.tabmix.setDefault", true);

  TM_setElements(true);

  TM_disableApply();

  // reset other settings to default
  var tmpPref = "extensions.tabmix.";
  for (var i = 0; i < otherPref.length; ++i )
    if (gPref.prefHasUserValue(tmpPref+otherPref[i])) gPref.clearUserPref(tmpPref+otherPref[i]);

  gPref.clearUserPref("extensions.tabmix.setDefault");
  callUpdateSettings();

  nsIPrefServiceObj.savePrefFile(null); // store the pref immediately
}

function getPrefByType(prefName) {
   try {
      switch (gPref.getPrefType(prefName)) {
         case pBranch.PREF_BOOL:
            return gPref.getBoolPref(prefName);
         case pBranch.PREF_INT:
            return gPref.getIntPref(prefName);
         case pBranch.PREF_STRING:
            return gPref.getCharPref(prefName);
      }
   } catch (e) {tmLog("error in getPrefByType " + "\n" + "caller " + getPrefByType.caller.name + "\n"+ prefName + "\n" + e);}
   return null;
}

function setPrefByType(prefName, newValue, atImport) {
   try {
      switch (gPref.getPrefType(prefName)) {
         case pBranch.PREF_BOOL:
            if (atImport)
               newValue = /true/i.test(newValue);
            gPref.setBoolPref(prefName, newValue);
            break;
         case pBranch.PREF_INT:
            gPref.setIntPref(prefName, newValue);
            break;
         case pBranch.PREF_STRING:
            // in prev version we use " " for to export string to file
            if (atImport && newValue.indexOf('"') == 0) 
               newValue = newValue.substring(1,newValue.length-1);
            gPref.setCharPref(prefName, newValue);
            break;
         default:
            if (!atImport)
               break;
            // we need to check when import from saved file
            // in 0.3.0.605 we changed tab color from old pref to new pref
            // old pref "extensions.tabmix.currentColor" type integer
            // new pref "extensions.tabmix.currentColorCode" type string
            if (prefName == "extensions.tabmix.currentColor" ||
                prefName == "extensions.tabmix.unreadColor" ||
                prefName == "extensions.tabmix.progressColor") {
                var colorCodes = ["#CF1919", "#0E36EF", "#DDDF0D", "#3F8F3E", "#E066FF", "#86E7EF",
                                   "#FFFFFF", "#7F7F7F", "#000000", "#EF952C", "#FF82AB", "#7F4C0F", "#AAAAFF"]
                gPref.setCharPref(prefName + "Code", colorCodes[newValue]);
            }
      }
   } catch (e) {tmLog("error in setPrefByType " + "\n" + "caller " + setPrefByType.caller.name + "\n"+ prefName + "\n" + newValue + "\n" + e);}
}

function TM_setElements (restore, start) {
   for (var i = 0; i < gPrefs.length; ++i ) {
      var item = gPrefs[i];
      var pref = item.getAttribute("prefstring");

      if (restore && gPref.prefHasUserValue(pref)) 
         gPref.clearUserPref(pref);

      var prefValue = getPrefByType(pref);
      switch (item.localName) {
         case "checkbox":
            if (item.hasAttribute("inverted"))
               prefValue = !prefValue;
            item.checked = prefValue;
            break;
         case "radiogroup":
            if (item.hasAttribute("boolean"))
               prefValue = prefValue ? 0 : 1;
            item.selectedIndex = prefValue;
            break;
         default:
            item.value = prefValue;
      }
   }

   setSelectedIndex(document.getElementById("tabclicking_tabbox").selectedIndex);
   TM_Options.checkDependant(start);
}

function exportData() {

  TM_EMsave();

  var patterns=new Array;
  patterns[0]='tabmixplus';
  var z=1, pref;

  for (var i = 0; i < gPrefs.length; ++i ) {
     pref = gPrefs[i].getAttribute("prefstring");
     patterns[z++] = pref + "=" + getPrefByType(pref);
  }

  // more pref to save
  for (i = 0; i < otherPref.length; ++i ){
    pref = "extensions.tabmix." + otherPref[i];
    patterns[z++] = pref + "=" + getPrefByType(pref);
  }

  saveToFile(patterns);
  return true;
}

function saveToFile (patterns) {
  // thanks to adblock
  var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(Components.interfaces.nsIFilePicker);
  var stream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);

  fp.init(window, null, fp.modeSave);
  fp.defaultExtension='txt';
  fp.defaultString='TMPpref';
  fp.appendFilters(fp.filterText);

  if (fp.show() != fp.returnCancel) {
    if (fp.file.exists()) fp.file.remove(true);
    fp.file.create(fp.file.NORMAL_FILE_TYPE, 0666);
    stream.init(fp.file, 0x02, 0x200, null);

    for (var i = 0; i < patterns.length ; i++) {
      patterns[i]=patterns[i]+"\n";
      stream.write(patterns[i], patterns[i].length);
    }

    stream.close();
  }
}

function importData () {
   var pattern = loadFromFile();

   if (!pattern) return false;
   var i, stringBundle;
   if(pattern[0]!="tabmixplus") {
      stringBundle = document.getElementById("tmp-string-bundle");
      //  Can not import because it is not a valid file.
      alert(stringBundle.getString("tmp.importPref.error1"));
      return false;
   }

   // set flag to prevent TMupdateSettings from run for each change
   gPref.setBoolPref("extensions.tabmix.setDefault", true);
   var prefName, prefValue;
   for (i=1; i<pattern.length; i++){
      var index = pattern[i].indexOf("=");
      if (index > 0){
         prefName  = pattern[i].substring(0,index);
         prefValue = pattern[i].substring(index+1,pattern[i].length);
         setPrefByType(prefName, prefValue, true);
      }
   }
   gPref.clearUserPref("extensions.tabmix.setDefault");
   prevWindow.TMP_SessionStore.setService(2, false, window);
   callUpdateSettings();

   nsIPrefServiceObj.savePrefFile(null); // store the pref immediately

   TM_setElements(false);

   TM_disableApply();

   return true;
}

function loadFromFile() {
   // thanks to adblock
   var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(Components.interfaces.nsIFilePicker);
   var stream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
   var streamIO = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);

   fp.init(window, null, fp.modeOpen);
   fp.defaultExtension='txt';
   fp.appendFilters(fp.filterText);

   if (fp.show() != fp.returnCancel) {
      stream.init(fp.file, 0x01, 0444, null);
      streamIO.init(stream);
      var input = streamIO.read(stream.available());
      streamIO.close();
      stream.close();

      var linebreak = input.match(/(((\n+)|(\r+))+)/m)[1]; // first: whole match -- second: backref-1 -- etc..
      return input.split(linebreak);
   }
   return null;
}


//xxx
function keyPressInText(event) {
   if(event.target.localName != "textbox")
      return;

   if(event.target.getAttribute("preftype") != "int")
      return;

   event.target.oldvalue = event.target.value;
   if (event.target.id == "ss_postdatabytes" && event.charCode == 45) {
      event.target.value = "";
      return;
   }

   if(event.charCode) {
     var key = String.fromCharCode(event.charCode).match(/\d/g);
     if (!key) {
         event.preventDefault();
         event.stopPropagation();
     }
   }
}

var applyData = [];
function TM_enableApply(event) {
   // if we fail once no neet to continue and we keep the apply button enable
   if ("undefined" in applyData)
      return;

   var item = event.target;
   var n = item.localName;

   // fix "-" in ss_postdatabytes to allow "-1"
   if (item.id == "ss_postdatabytes" && item.value.length > 1) {
      var val = item.value;

      if (val.length == 2 && val.indexOf("-") == 0 && val != "-1")
         event.target.value = "-1";

      if (val.length > 2 && val.indexOf("-") == 0)
         event.target.value = val.substr(2);
   }
   
   // only allow event from this item to go on....
   if (item.parentNode.id == "tm-settings")
      return;
   if (n != "radio" && n != "menuitem" && 
              n != "checkbox" && n != "textbox")
      return;
   // update tabclicking option
   var aItemID = item.parentNode.parentNode.id;
   if (aItemID == "ClickTab" || aItemID == "ClickTabbar") {
      var c = ["dbl", "middle", "ctrl", "shift", "alt"];
      var index = document.getElementById("tabclicking_tabbox").selectedIndex;
      item = document.getElementById(c[index] + aItemID);
      item.value = document.getElementById(aItemID).value;
   }
   else
      while(item.id != "pref-tabmix" && !item.hasAttribute("prefstring"))
         item = item.parentNode;

   if (item.hasAttribute("prefstring"))
      updateApplyData(item);
   else {
      tmLog("erorr in tabmix options, item.id " + event.target.id + "\n has no prefstring");
      applyData["undefined"] = true;
      document.documentElement.getButton("extra1").disabled = false;
      return;
   }
}

// return value from item
function getValue(item) {
   var newValue;
   if (item.localName == "checkbox")
      newValue = item.hasAttribute("inverted") ? !item.checked : item.checked;
   else
      newValue = item.value;

   return newValue;
}

function updateApplyData(item) {
   var newValue = getValue(item);
   var pref = item.getAttribute("prefstring");
   var savedValue = getPrefByType(pref);

   if (savedValue != newValue)
      applyData[pref] = newValue;
   else if (pref in applyData)
      delete applyData[pref];

   var applyCount = 0;
   for (var n in applyData) {
      if (++applyCount > 0)
         break;
   }

   var applyButton = document.documentElement.getButton("extra1");
   if (applyButton.disabled != (applyCount == 0))
      applyButton.disabled = applyCount == 0;
}

function TM_disableApply() {
   document.documentElement.getButton("extra1").disabled = true;
   applyData = [];
}

function setLastTab() {
   gPref.setIntPref("extensions.tabmix.selected_tab", document.getElementById("tabMixTabBox").selectedIndex);

   var subtabs = document.getElementsByAttribute("subtub", "true");
   var subTab = "extensions.tabmix.selected_sub_tab";
   for (var i = 0; i < subtabs.length; i++)
      gPref.setIntPref(subTab + subtabs[i].getAttribute("value"), subtabs[i].selectedIndex);

   // remove EventListener when we exit
   window.removeEventListener("command", TM_enableApply, false);
   window.removeEventListener("input", TM_enableApply, false);
   window.removeEventListener("keypress", keyPressInText, false);   
}

function getTab() {
   var selTabindex = prevWindow.TMP_getIntPref("", "extensions.tabmix.selected_tab" , 0);
   TM_selectTab(selTabindex);

   var subtabs = document.getElementsByAttribute("subtub", true);
   var subTab = "extensions.tabmix.selected_sub_tab";
   for (var i = 0; i < subtabs.length; i++) {
      var val = prevWindow.TMP_getIntPref("" ,subTab + subtabs[i].getAttribute("value"), 0);
      subtabs[i].selectedIndex = val;
   }
}

// this function is called from here and from TMP_openDialog if the dialog already opened
function TM_selectTab(aSelTab) {
  document.getElementById("tabMixTabBox").selectedIndex = (aSelTab) ? aSelTab : 0;
  var tabId = document.getElementsByTagName("tab")[aSelTab].id;
  var catButtons = document.getElementById("TM_ButtonBox").childNodes;

  for(var i = 0; i < catButtons.length; i++)
    if(catButtons[i].getAttribute('group', 'categories'))
      catButtons[i].setAttribute('checked', (catButtons[i].id == 'button' + tabId));
}

function showIncompatible() {
   if (prevWindow) {
      var result = prevWindow.disableExtensions(this);
      if (result) {
         document.getElementById("incompatible").collapsed = true;
         sizeToContent();
      }
      this.focus();
   }
   else {
      var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                                    .getService(Components.interfaces.nsIPromptService);
      var stringBundle = document.getElementById("tmp-string-bundle");
      var title = stringBundle.getString("tabmixoption.error.title");
      var msg = stringBundle.getString("tabmixoption.error.msg");
      promptService.alert(window, title, msg);
      window.close();
   }
}

function tabSelectionChanged(event) {
   if (event && event.target.localName != "tabs")
      return;

   var index = event.target.parentNode.selectedIndex;
   setVisibility(index);
   setSelectedIndex(index);
}

function setVisibility(index) {
   if (index == 1) {
      TM_Options.setItem("contentLoad", "style", "visibility: visible");
      TM_Options.disabled("contentLoad");
   }
   else {
      TM_Options.setItem("contentLoad", "style", "visibility: hidden");
      document.getElementById("obs_contentLoad").removeAttribute("disabled");
   }
}

function setSelectedIndex(index) {
   var c = ["dbl", "middle", "ctrl", "shift", "alt"];
   document.getElementById("ClickTab").value = document.getElementById(c[index] + "ClickTab").value;
   document.getElementById("ClickTabbar").value = document.getElementById(c[index] +"ClickTabbar").value;
}
